package com.tina.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author tina
 * @Time 2020/11/29 下午3:31
 * @Version 1.0
 * @Content rocketMQ 工具类
 **/
@Component
@Slf4j
public class MqUtil {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送延迟消息
     * "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h"
     * 现在RocketMq并不支持任意时间的延时，需要设置几个固定的延时等级，从1s到2h分别对应着等级1到18
     *
     * @param topic
     * @param tag
     * @param keys
     * @param body
     */
    public void sendAffairMsg(String topic, String tag, String keys, String body) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message message = new Message(topic, tag, keys, body.getBytes());
        message.setDelayTimeLevel(16);
        SendResult send = rocketMQTemplate.getProducer().send(message);
        log.info("affairSendMsg->{}", send);
    }


    /**
     * 发送普通消息
     *
     * @param topic
     * @param tag
     * @param keys
     * @param body
     */
    public void sendMsg(String topic, String tag, String keys, String body) throws Exception {
        Message message = new Message(topic, tag, keys, body.getBytes());
        SendResult send = rocketMQTemplate.getProducer().send(message);
        log.info("sendMsg->{}", send);
    }


}
